1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
|
// app/pdftron-viewer/page.tsx
"use client"
import * as React from "react"
import { useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { ArrowLeft, MessageSquare, Download, Upload } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { useSession } from "next-auth/react"
import { useToast } from "@/hooks/use-toast"
import type { WebViewerInstance } from "@pdftron/webviewer"
// PDFTron 코멘트 타입 정의
interface PDFTronComment {
id: number
documentReviewId: number
pdftronDocumentId: string
xfdfString: string
annotationData: any
commentSummary?: {
total: number
open: number
resolved: number
rejected: number
deferred: number
byCategory: Record<string, number>
bySeverity: Record<string, number>
byAuthor: Record<string, number>
}
createdBy: number
createdByName?: string
createdByType: "buyer" | "vendor"
createdAt: Date
updatedAt: Date
}
export default function PDFTronViewerPage() {
const { data: session, status } = useSession()
const searchParams = useSearchParams()
const viewerRef = React.useRef<HTMLDivElement>(null)
const [instance, setInstance] = React.useState<WebViewerInstance | null>(null)
const [isLoading, setIsLoading] = React.useState(true)
const [lastSavedTime, setLastSavedTime] = React.useState<Date | null>(null)
const [isSaving, setIsSaving] = React.useState(false)
const [annotationCount, setAnnotationCount] = React.useState(0)
const { toast } = useToast()
const initialized = React.useRef(false)
const isCancelled = React.useRef(false)
const autoSaveTimerRef = React.useRef<NodeJS.Timeout | null>(null)
const xfdfLoadedRef = React.useRef(false) // XFDF 로딩 완료 여부 추적
// URL 파라미터에서 정보 가져오기
const filePath = searchParams.get('filePath')
const documentId = searchParams.get('documentId')
const documentReviewId = searchParams.get('documentReviewId')
const sessionId = searchParams.get('sessionId')
const documentName = searchParams.get('documentName')
// PDFTron WebViewer 초기화 - session과 XFDF 모두 준비된 후 실행
React.useEffect(() => {
if (!initialized.current && viewerRef.current && filePath && session && documentReviewId) {
initialized.current = true
isCancelled.current = false
// XFDF 먼저 로드한 후 WebViewer 초기화
loadAndInitializeViewer()
}
return () => {
if (instance) {
try {
instance.UI.dispose()
} catch (error) {
console.warn("Error disposing viewer:", error)
}
}
isCancelled.current = true
// 타이머 정리
if (autoSaveTimerRef.current) {
clearTimeout(autoSaveTimerRef.current)
}
}
}, [filePath, session, documentReviewId, sessionId])
const loadAndInitializeViewer = async () => {
try {
// 1. 먼저 기존 XFDF 로드
let existingXFDF = ""
try {
const response = await fetch(`/api/pdftron-comments/xfdf?documentReviewId=${documentReviewId}`)
if (response.ok) {
const data = await response.json()
if (data.xfdfString) {
existingXFDF = data.xfdfString
console.log("Loaded existing XFDF successfully")
}
}
} catch (error) {
console.error("Failed to load XFDF:", error)
}
// 2. WebViewer 초기화
await initializeWebViewer(existingXFDF)
} catch (error) {
console.error("Failed to initialize viewer:", error)
setIsLoading(false)
toast({
title: "Error",
description: "Failed to initialize document viewer",
variant: "destructive"
})
}
}
const initializeWebViewer = async (existingXFDF: string) => {
try {
console.log("Starting WebViewer initialization...")
console.log("File path:", filePath)
console.log("Current session:", session)
console.log("Has existing XFDF:", !!existingXFDF)
// 동적 import 사용
const { default: WebViewer } = await import("@pdftron/webviewer")
if (isCancelled.current || !viewerRef.current) {
console.log("WebViewer initialization cancelled")
return
}
// WebViewer 인스턴스 생성
const webviewerInstance = await WebViewer(
{
path: "/pdftronWeb",
licenseKey: process.env.NEXT_PUBLIC_PDFTRON_LICENSE_KEY || process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY,
initialDoc: filePath!,
},
viewerRef.current
)
if (isCancelled.current) {
console.log("WebViewer initialization cancelled after creation")
return
}
setInstance(webviewerInstance)
if (!webviewerInstance.Core) {
console.error("WebViewer Core is not available")
setIsLoading(false)
return
}
const { documentViewer, annotationManager, Annotations } = webviewerInstance.Core
// 현재 사용자 설정
const currentUser = session?.user?.email || session?.user?.name || 'Anonymous'
console.log("Setting current user:", currentUser)
annotationManager.setCurrentUser(currentUser)
// 권한 설정 - 자기 annotation만 수정/삭제 가능
annotationManager.setPermissionCheckCallback((author: string, annotation: any) => {
// 자기가 만든 annotation만 수정 가능
return author === currentUser
})
// 문서 로드 완료 시
documentViewer.addEventListener('documentLoaded', async () => {
console.log("Document loaded successfully")
setIsLoading(false)
console.log(existingXFDF)
// 기존 XFDF 적용
if (existingXFDF && !xfdfLoadedRef.current) {
console.log(existingXFDF, "existingXFDF")
try {
await annotationManager.importAnnotations(existingXFDF)
xfdfLoadedRef.current = true
console.log("Imported existing annotations from XFDF")
// 초기 annotation 수 설정
const annotations = annotationManager.getAnnotationsList()
setAnnotationCount(annotations.length)
// 마지막 저장 시간 설정
setLastSavedTime(new Date())
} catch (error) {
console.error("Failed to import XFDF:", error)
toast({
title: "Warning",
description: "Failed to load existing annotations",
variant: "destructive"
})
}
}
// UI 설정 (1초 지연)
setTimeout(() => {
setupUI()
}, 1000)
})
// UI 설정 함수
const setupUI = async () => {
try {
console.log("Setting up UI features...")
// Review 모드 annotation 도구 활성화
try {
// 주석 도구 활성화
webviewerInstance.UI.enableElements(['highlightToolButton'])
webviewerInstance.UI.enableElements(['stickyToolButton'])
webviewerInstance.UI.enableElements(['freeTextToolButton'])
webviewerInstance.UI.enableElements(['underlineToolButton'])
webviewerInstance.UI.enableElements(['strikeoutToolButton'])
webviewerInstance.UI.enableElements(['squigglyToolButton'])
// 노트 패널 열기
webviewerInstance.UI.openElements(['notesPanel'])
} catch (e) {
console.log("Could not enable annotation tools:", e)
}
// 커스텀 이벤트 리스너 설정
setupAnnotationListeners()
} catch (error) {
console.error("Error setting up UI:", error)
}
}
// Annotation 이벤트 리스너 설정
const setupAnnotationListeners = () => {
// 자동 저장 함수
const handleAutoSave = async () => {
if (!documentReviewId) {
console.log("No documentReviewId, skipping auto-save")
return
}
// 이미 저장 중이면 스킵
if (isSaving) {
console.log("Already saving, skipping...")
return
}
setIsSaving(true)
try {
const xfdfString = await annotationManager.exportAnnotations()
// Annotation 요약 정보 생성
const annotations = annotationManager.getAnnotationsList()
const summary = {
total: annotations.length,
open: annotations.filter((a: any) => a.getCustomData('status') !== 'resolved').length,
resolved: annotations.filter((a: any) => a.getCustomData('status') === 'resolved').length,
rejected: annotations.filter((a: any) => a.getCustomData('status') === 'rejected').length,
deferred: annotations.filter((a: any) => a.getCustomData('status') === 'deferred').length,
byCategory: {} as Record<string, number>,
bySeverity: {} as Record<string, number>,
byAuthor: {} as Record<string, number>
}
annotations.forEach((annotation: any) => {
const category = annotation.getCustomData('category') || 'general'
const severity = annotation.getCustomData('severity') || 'minor'
const author = annotation.Author || 'Anonymous'
summary.byCategory[category] = (summary.byCategory[category] || 0) + 1
summary.bySeverity[severity] = (summary.bySeverity[severity] || 0) + 1
summary.byAuthor[author] = (summary.byAuthor[author] || 0) + 1
})
// 서버에 저장
const response = await fetch('/api/pdftron-comments/xfdf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
documentReviewId: parseInt(documentReviewId),
sessionId: sessionId ? parseInt(sessionId) :0,
pdftronDocumentId: documentId,
xfdfString: xfdfString,
commentSummary: summary,
createdByType: 'buyer'
})
})
if (response.ok) {
setLastSavedTime(new Date())
setAnnotationCount(annotations.length)
console.log("Auto-save successful")
} else {
console.error("Auto-save failed")
toast({
title: "Error",
description: "Failed to save annotations",
variant: "destructive"
})
}
} catch (error) {
console.error("Auto-save error:", error)
toast({
title: "Error",
description: "Failed to save annotations",
variant: "destructive"
})
} finally {
setIsSaving(false)
}
}
// Annotation 변경 감지
annotationManager.addEventListener('annotationChanged', (annotations: any[], action: string) => {
if (action === 'add' || action === 'modify' || action === 'delete') {
// 새 annotation에 기본 메타데이터 추가
if (action === 'add') {
annotations.forEach(annotation => {
if (!annotation.getCustomData('category')) {
annotation.setCustomData('category', 'general')
annotation.setCustomData('severity', 'minor')
annotation.setCustomData('status', 'open')
annotation.setCustomData('createdBy', session?.user?.id || '')
annotation.setCustomData('createdByType', 'buyer')
annotation.setCustomData('createdAt', new Date().toISOString())
// 기본 색상 설정 (minor = yellow)
try {
if (Annotations) {
annotation.Color = new Annotations.Color(250, 204, 21)
}
} catch (e) {
console.log("Could not set annotation color")
}
}
})
}
// 자동 저장 - 2초 디바운싱
if (autoSaveTimerRef.current) {
clearTimeout(autoSaveTimerRef.current)
}
autoSaveTimerRef.current = setTimeout(() => {
console.log("Auto-saving annotations...")
handleAutoSave()
}, 2000)
}
})
// 코멘트 변경 감지
annotationManager.addEventListener('annotationCommentsChanged', () => {
// 자동 저장 - 1.5초 디바운싱
if (autoSaveTimerRef.current) {
clearTimeout(autoSaveTimerRef.current)
}
autoSaveTimerRef.current = setTimeout(() => {
console.log("Auto-saving comments...")
handleAutoSave()
}, 1500)
})
// Annotation 선택 시 기본값 설정
annotationManager.addEventListener('annotationSelected', (annotations: any, action: string) => {
if (annotations && annotations.length > 0) {
const annotation = annotations[0]
// 기본 커스텀 데이터 설정
if (!annotation.getCustomData('category')) {
annotation.setCustomData('category', 'general')
annotation.setCustomData('severity', 'minor')
annotation.setCustomData('status', 'open')
annotation.setCustomData('createdBy', session?.user?.id || '')
annotation.setCustomData('createdByType', 'buyer')
annotation.setCustomData('createdAt', new Date().toISOString())
}
}
})
}
} catch (error) {
console.error("WebViewer initialization failed:", error)
setIsLoading(false)
toast({
title: "Error",
description: "Failed to initialize document viewer",
variant: "destructive"
})
}
}
// 통계 정보 가져오기
const getAnnotationStats = () => {
if (!instance) return null
const { annotationManager } = instance.Core
const annotations = annotationManager.getAnnotationsList()
return {
total: annotations.length,
open: annotations.filter((a: any) => a.getCustomData('status') !== 'resolved').length,
resolved: annotations.filter((a: any) => a.getCustomData('status') === 'resolved').length
}
}
// 시간 포맷팅
const formatLastSaved = () => {
if (!lastSavedTime) return null
const now = new Date()
const diff = Math.floor((now.getTime() - lastSavedTime.getTime()) / 1000)
if (diff < 60) return "Just saved"
if (diff < 3600) return `Saved ${Math.floor(diff / 60)} min ago`
if (diff < 86400) return `Saved ${Math.floor(diff / 3600)} hours ago`
return `Saved ${Math.floor(diff / 86400)} days ago`
}
const stats = getAnnotationStats()
const lastSavedText = formatLastSaved()
return (
<div className="flex flex-col h-screen overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b bg-background flex-shrink-0">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="sm"
onClick={() => window.close()}
>
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
<div>
<h1 className="text-lg font-semibold">{documentName || 'Document Viewer'}</h1>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>Review Mode</span>
<span>•</span>
<span>User: {session?.user?.email || session?.user?.name || 'Loading...'}</span>
{stats && stats.total > 0 && (
<>
<span>•</span>
<Badge variant="outline">
<MessageSquare className="h-3 w-3 mr-1" />
{stats.open} open / {stats.total} total
</Badge>
</>
)}
{isSaving && (
<>
<span>•</span>
<Badge variant="outline" className="text-blue-600 border-blue-600">
<div className="animate-pulse">Auto-saving...</div>
</Badge>
</>
)}
{!isSaving && lastSavedText && (
<>
<span>•</span>
<Badge variant="outline" className="text-green-600 border-green-600">
✓ {lastSavedText}
</Badge>
</>
)}
</div>
</div>
</div>
</div>
{/* PDFTron Viewer */}
<div className="flex-1 relative overflow-hidden">
{(isLoading || status === "loading") && (
<div className="absolute inset-0 flex items-center justify-center bg-background/80 z-10">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
<p className="text-sm text-muted-foreground">
{status === "loading" ? "Loading session..." : "Loading document..."}
</p>
<p className="text-xs text-muted-foreground mt-1">
Initializing PDFTron viewer...
</p>
</div>
</div>
)}
<div
ref={viewerRef}
className="h-full w-full"
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
}}
/>
</div>
</div>
)
}
|